package com.zp.qualitypractice.mvp4;

import android.os.Bundle;

import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * Created by izp on 2017/7/5.
 */

public class Presenter<V extends MVPBase.BaseView> implements MVPBase.BasePresenter<V> {
    protected Reference<V> mViewRef; //View 接口类型的弱引用
    protected CompositeDisposable mCompositeDisposable;
    protected LifecycleProvider<ActivityEvent> mLifeProvider;

    public Presenter(V view) {
        if (null!=mViewRef){
            mViewRef = new WeakReference<V>(view);
        }
    }

    @Override
    public void attachView(V view, Bundle bundle) {
        if (null!=mViewRef){
            mViewRef = new WeakReference<V>(view);
        }
    }

    @Override
    public void detachView() {
        unDisposable();
        if (mViewRef != null) {
            mViewRef.clear();
            mViewRef = null;
        }
    }

    protected V getView() {
        return null==mViewRef?null:mViewRef.get();
    }

    protected Presenter bindToLife(LifecycleProvider<ActivityEvent> provider) {
        this.mLifeProvider = provider;
        return this;
    }

    protected LifecycleProvider<ActivityEvent> getLifeProvider() {
        return mLifeProvider;
    }

    protected void addDisposable(Disposable disposable) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(disposable);
    }

    private void unDisposable() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();
        }
    }
}
